<?php

namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;

use App\Common\ErrorDefine;
class Controller extends BaseController
{
    static function ShowError($errorCode, $errorMessage = "")
    {
        if(empty($errorMessage)) {
            $errorMessage = ErrorDefine::errorMessage($errorCode);
        }
        $message = array(
            'error_code' => $errorCode,
            'error_message' => $errorMessage
        );
        self::ShowMessageDiy($message);
    }

    //只需传$data
    static function ShowMessage($data = '',$error_code =0,$error_message ='')
    {
        if ($data){
            $message = array(
                'error_code' => $error_code,
                'error_message' => $error_message,
                'data' => $data
            );
        }else {
            $message = array(
                'error_code' => $error_code,
                'error_message' => $error_message,
            );
        }


        $http_body = stripslashes(self::decodeUnicode(json_encode($message)));
        $content_len = strlen($http_body);
        header("Content-type: application/json;charset=UTF-8");
        header("Content-Length: $content_len");
        echo $http_body;
    }


    /*
 * 汉字编码处理
 */
    static function decodeUnicode($str) {
        return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function( '$matches', 'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");' ), $str);
    }

    static function ShowMessageDiy($message = null)
    {
        if($message == null) {
            $message = array(
                'error_code' => 0,
                'error_message' => '',
                'data' => ''
            );
        }

        $http_body = stripslashes(self::decodeUnicode(json_encode($message)));
        $content_len = strlen($http_body);
        header("Content-type: application/json;charset=UTF-8");
        header("Content-Length: $content_len");
        echo $http_body;
    }


}
